//
//  FDrawableImageView.m
//  Foundation
//
//  Created by 吴新庭 on 2019/9/3.
//

#import "FDrawableImageView.h"
#import "FDrawView.h"

static CGFloat const kDefaultPaintWidth = 6.f;
@interface FDrawableImageView ()

@property (nonatomic, strong) FDrawView *drawView;

@end

@implementation FDrawableImageView

- (instancetype)initWithImage:(UIImage *)image {
    if (self = [super initWithImage:image]) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setEdit:(BOOL)edit {
    _edit = edit;
    
    self.userInteractionEnabled = edit;
    self.drawView.drawable = edit;
}

- (UIImage *)drawedImage {
    UIGraphicsBeginImageContext(self.image.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (void)setTransform:(CGAffineTransform)transform {
    [super setTransform:transform];
    
    self.drawView.paintWidth = MAX(1.f, kDefaultPaintWidth / transform.a);
}

- (void)clean {
    [self.drawView clean];
}

#pragma mark - Private
- (void)setup {
    [self addSubview:self.drawView];
    [self.drawView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(0);
    }];
}

- (FDrawView *)drawView {
    if (!_drawView) {
        _drawView = [[FDrawView alloc] init];
        _drawView.paintColor = [UIColor redColor];
        _drawView.paintWidth = kDefaultPaintWidth;
    }
    return _drawView;
}

@end
